package uml2Java;


import java.io.File;
import java.io.IOException;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EPackage.Registry;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;

import astjava.JavaPackage;
import astjava.Model;

public class JavaChargeur {
	
	protected String _path;

	public JavaChargeur(String path) {
		_path = path;
	}

	public Resource loadResource() {
		ResourceSet resourceSet = new ResourceSetImpl();
		URI fileURI =  URI.createFileURI(new File(_path).getAbsolutePath());
		Registry packageRegistry = resourceSet.getPackageRegistry();
		packageRegistry.put(JavaPackage.eNS_URI, JavaPackage.eINSTANCE);
		Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("astjava", new XMIResourceFactoryImpl());

		Resource poResource = resourceSet.getResource(fileURI, true);
		return poResource;
	}

	public Model loadJavaModel() {
		return (Model) loadResource().getContents().get(0);
	}

	public void save(Model javaModel) {
		ResourceSet resourceSet = new ResourceSetImpl();
	   	URI uri = URI.createFileURI(new File(_path).getAbsolutePath());
	   	Registry packageRegistry = resourceSet.getPackageRegistry();
		packageRegistry.put(JavaPackage.eNS_URI, JavaPackage.eINSTANCE);
		Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("astjava", new XMIResourceFactoryImpl());
        Resource resource = new ResourceSetImpl().createResource(uri);
        resource.getContents().add(javaModel);
           try {
                resource.save(null);

           } catch (IOException ioe) {
               	System.err.println(ioe.getMessage());
           }
    }

}

